package com.jpcc.vw.onlineRadio.utils;

import android.text.TextUtils;
import android.view.View;

import com.google.gson.Gson;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.jpcc.vw.onlineRadio.R;
import com.jpcc.vw.onlineRadio.activity.PlayHistoryActivity;
import com.jpcc.vw.onlineRadio.application.MusicApplication;
import com.jpcc.vw.onlineRadio.db.DatabaseHelperOrm;
import com.jpcc.vw.onlineRadio.http.HttpClient;
import com.jpcc.vw.onlineRadio.model.IRadio;
import com.jpcc.vw.onlineRadio.model.bean.BaseBean;
import com.jpcc.vw.onlineRadio.model.bean.DeletePlayHistoryEntity;
import com.jpcc.vw.onlineRadio.model.bean.PlayHistoryEntity;
import com.jpcc.vw.onlineRadio.model.bean.PlayHistoryOnlineBean;
import com.jpcc.vw.onlineRadio.model.bean.PlayHistoryOnlineEntity;
import com.jpcc.vw.onlineRadio.model.bean.RecentAlbumRadioTrackBean;
import com.jpcc.vw.onlineRadio.model.bean.RecentAlbumRadioTrackOnlineBean;
import com.jpcc.vw.onlineRadio.model.impl.RadioImpl;
import com.orhanobut.logger.Logger;
import com.zhy.http.okhttp.callback.StringCallback;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

public class SyncHisUtils {


    private static void getData() {
        IRadio model = new RadioImpl();
        model.getPlayHistory().subscribe(new CommonSubscriber<PlayHistoryOnlineBean>() {
            @Override
            public void onSuccess(PlayHistoryOnlineBean response) {
                DatabaseHelperOrm helper = DatabaseHelperOrm.getHelper(MusicApplication.GetInstance());
                DeleteBuilder deleteBuilder = null;
                if (response.getData() != null) {
                    try {
                        deleteBuilder = helper.getRecentOnlineDao().deleteBuilder();
                        deleteBuilder.where().eq("userId", MusicApplication.GetUserId());
                        deleteBuilder.delete();


                        deleteBuilder = helper.getRecentDao().deleteBuilder();
                        deleteBuilder.where().eq("userId", MusicApplication.GetUserId());
                        deleteBuilder.delete();

                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                    try {
                        for (PlayHistoryOnlineEntity entityOnline : response.getData()) {
                            RecentAlbumRadioTrackOnlineBean localData = new RecentAlbumRadioTrackOnlineBean();
                            localData.setUserId(MusicApplication.GetUserId());
                            if (entityOnline.getContentType() == 1) {
                                localData.setType("album");
                            } else {
                                localData.setType("radio");
                            }
                            if (entityOnline.getContentType() == 1) {
                                if (entityOnline.getAlbum() != null && entityOnline.getTrack() != null) {
                                    localData.setTrackId(entityOnline.getTrack().getId());
                                    localData.setTrackName(entityOnline.getTrack().getTitle());
                                    if (entityOnline.getTrack() != null && entityOnline.getTrack().getPlayInfo() != null && entityOnline.getTrack().getPlayInfo().getDownloadUrl() != null) {
                                        localData.setDownloadUrl(entityOnline.getTrack().getPlayInfo().getDownloadUrl().getUrl());
                                    }
                                    localData.setTrackUrl(entityOnline.getTrack().getPlayUrl32());
                                    localData.setDuration((int) entityOnline.getTrack().getDuration());
                                    localData.setCurrentDuration(entityOnline.getPlayedSecs() * 1000);
                                    localData.setAlbumId(entityOnline.getAlbum().getId());
                                    localData.setCover(entityOnline.getAlbum().getCoverUrlLarge());
                                    localData.setAlbumName(entityOnline.getAlbum().getTitle());
                                    localData.setAuthor("");
                                    localData.setVipFree(entityOnline.getAlbum().isVipFree());
                                }

                            } else {
                                if (entityOnline.getRadio() != null && entityOnline.getProgram() != null) {
                                    localData.setAlbumId(entityOnline.getRadio().getId());
                                    localData.setCover(entityOnline.getRadio().getLarge_cover_url());
                                    localData.setAlbumName(entityOnline.getRadio().getName());
                                    localData.setAuthor("");
                                    localData.setTrackId(entityOnline.getProgram().getId());
                                    if (!TextUtils.isEmpty(entityOnline.getProgram().getProgram_name())) {
                                        localData.setTrackName(entityOnline.getProgram().getProgram_name());
                                    } else if (!TextUtils.isEmpty(entityOnline.getRadio().getPlaying_program_name())) {
                                        localData.setTrackName(entityOnline.getRadio().getPlaying_program_name());
                                    } else {
                                        localData.setTrackName("");
                                    }
                                    localData.setLive(true);
                                }
                            }
                            localData.setFrom(4);
                            localData.setTimeStamp(entityOnline.getStartedAt());
                            helper.getRecentOnlineDao().create(localData);
                        }

                        for (PlayHistoryOnlineEntity entityOnline : response.getData()) {
                            RecentAlbumRadioTrackBean localData = new RecentAlbumRadioTrackBean();
                            localData.setUserId(MusicApplication.GetUserId());
                            if (entityOnline.getContentType() == 1) {
                                localData.setType("album");
                            } else {
                                localData.setType("radio");
                            }
                            if (entityOnline.getContentType() == 1) {
                                if (entityOnline.getAlbum() != null && entityOnline.getTrack() != null) {
                                    localData.setTrackId(entityOnline.getTrack().getId());
                                    localData.setTrackName(entityOnline.getTrack().getTitle());
                                    if (entityOnline.getTrack() != null && entityOnline.getTrack().getPlayInfo() != null && entityOnline.getTrack().getPlayInfo().getDownloadUrl() != null) {
                                        localData.setDownloadUrl(entityOnline.getTrack().getPlayInfo().getDownloadUrl().getUrl());
                                    }
                                    localData.setTrackUrl(entityOnline.getTrack().getPlayUrl32());
                                    localData.setDuration((int) entityOnline.getTrack().getDuration());
                                    localData.setCurrentDuration(entityOnline.getPlayedSecs() * 1000);
                                    localData.setAlbumId(entityOnline.getAlbum().getId());
                                    localData.setCover(entityOnline.getAlbum().getCoverUrlLarge());
                                    localData.setAlbumName(entityOnline.getAlbum().getTitle());
                                    localData.setAuthor("");
                                    localData.setVipFree(entityOnline.getAlbum().isVipFree());
                                }

                            } else {
                                if (entityOnline.getRadio() != null && entityOnline.getProgram() != null) {
                                    localData.setAlbumId(entityOnline.getRadio().getId());
                                    localData.setCover(entityOnline.getRadio().getLarge_cover_url());
                                    localData.setAlbumName(entityOnline.getRadio().getName());
                                    localData.setAuthor("");
                                    localData.setTrackId(entityOnline.getProgram().getId());
                                    if (!TextUtils.isEmpty(entityOnline.getProgram().getProgram_name())) {
                                        localData.setTrackName(entityOnline.getProgram().getProgram_name());
                                    } else if (!TextUtils.isEmpty(entityOnline.getRadio().getPlaying_program_name())) {
                                        localData.setTrackName(entityOnline.getRadio().getPlaying_program_name());
                                    } else {
                                        localData.setTrackName("");
                                    }
                                    localData.setLive(true);
                                }
                            }
                            localData.setFrom(4);
                            localData.setTimeStamp(entityOnline.getStartedAt());
                            helper.getRecentDao().create(localData);
                        }

                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(BaseBean response) {
            }
        });
    }


    public static void doSyncHistory() {
        DatabaseHelperOrm helper = DatabaseHelperOrm.getHelper(MusicApplication.GetInstance());
        List<RecentAlbumRadioTrackOnlineBean> onlineHis = new ArrayList<>();
        List<RecentAlbumRadioTrackBean> localHis = new ArrayList<>();
        IRadio model = new RadioImpl();
        try {
            onlineHis = helper.getRecentOnlineDao().queryBuilder().orderBy("timeStamp", false).where().eq("userId", MusicApplication.GetUserId()).query();
            localHis = helper.getRecentDao().queryBuilder().orderBy("timeStamp", false).where().eq("userId", MusicApplication.GetUserId()).query();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        //没有数据 这个时候从接口端拿到数据 并且覆盖 RecentAlbumRadioTrackOnlineBean这个表
        if (onlineHis.size() == 0 && localHis.size() == 0) {
            getData();
        } else {
            List<Long> localIds = new ArrayList<>();
            for (RecentAlbumRadioTrackBean locals : localHis) {
                localIds.add(locals.getTrackId());
            }
            List<RecentAlbumRadioTrackOnlineBean> toDeleteBeans = new ArrayList<>();
            for (RecentAlbumRadioTrackOnlineBean online : onlineHis) {
                if (!localIds.contains(online.getTrackId())) {
                    toDeleteBeans.add(online);
                }

            }


            //待删除的数目为0 表示不删除 直接把本地的数据同步到云端
            if (toDeleteBeans.size() == 0) {

                if (localHis.size() > 0) {



                    List<PlayHistoryEntity> history = new ArrayList<>();
                    for (RecentAlbumRadioTrackBean recent : localHis) {
                        if (history.size() > 20) {
                            break;
                        }
                        PlayHistoryEntity entity = new PlayHistoryEntity();
                        if ("album".equals(recent.getType())) {
                            entity.setContentType(1);
                            entity.setAlbumId(recent.getAlbumId());
                            entity.setTrackId(recent.getTrackId());
                            entity.setAlbumTitle(recent.getAlbumName());
                            entity.setTrackTitle(recent.getTrackName());
                            entity.setPlayBeginAt(recent.getTimeStamp());
                            if (recent.getCurrentDuration() / 1000 == 0) {
                                entity.setPlayedSecs(1);
                            } else {
                                entity.setPlayedSecs(recent.getCurrentDuration() / 1000);
                            }
                            entity.setPlayEndAt(entity.getPlayBeginAt() + entity.getPlayedSecs() * 1000);
                            entity.setTrackCoverUrlLarge(recent.getCover());
                        } else {
                            entity.setContentType(2);
                            entity.setRadioId(recent.getAlbumId());
                            entity.setScheduleId(recent.getTrackId());
                            entity.setRadioName(recent.getAlbumName());
                            entity.setProgramName(recent.getTrackName());
                            entity.setPlayBeginAt(recent.getTimeStamp());
                            if (recent.getCurrentDuration() / 1000 == 0) {
                                entity.setPlayedSecs(1);
                            } else {
                                entity.setPlayedSecs(recent.getCurrentDuration() / 1000);
                            }
                            entity.setPlayEndAt(entity.getPlayBeginAt() + entity.getPlayedSecs() * 1000);
                            entity.setRadioCoverUrlLarge(recent.getCover());
                        }
                        history.add(entity);
                    }








                    HttpClient.SyncPlayHistory(new Gson().toJson(history), new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                        }

                        @Override
                        public void onResponse(String response, int id) {
                            Logger.i(response.toString());
                            BaseBean resBean = new Gson().fromJson(response, BaseBean.class);
                            if (resBean.getCode() == 0) {
                                getData();
                            }
                        }
                    });
                } else {
                    getData();
                }
            }
            //需要先删除 后同步 再然后覆盖
            else {
                List<RecentAlbumRadioTrackBean> finalLocalHis = localHis;


                List<DeletePlayHistoryEntity> deletes = new ArrayList<>();
                for (RecentAlbumRadioTrackBean bean:finalLocalHis){
                    DeletePlayHistoryEntity historyEntity = new DeletePlayHistoryEntity();
                    if("album".equals(bean.getType())){
                        historyEntity.setContentType(1);
                        historyEntity.setAlbumId(bean.getAlbumId());
                        historyEntity.setTrackId(bean.getTrackId());
                    }
                    else{
                        historyEntity.setContentType(2);
                        historyEntity.setRadioId(bean.getAlbumId());
                        historyEntity.setScheduleId(bean.getTrackId());
                    }
                    deletes.add(historyEntity);
                }


                HttpClient.DeletePlayHistory(new Gson().toJson(deletes), new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        if (finalLocalHis.size() > 0) {

                            List<PlayHistoryEntity> history = new ArrayList<>();
                            for (RecentAlbumRadioTrackBean recent : finalLocalHis) {
                                if (history.size() > 20) {
                                    break;
                                }
                                PlayHistoryEntity entity = new PlayHistoryEntity();
                                if ("album".equals(recent.getType())) {
                                    entity.setContentType(1);
                                    entity.setAlbumId(recent.getAlbumId());
                                    entity.setTrackId(recent.getTrackId());
                                    entity.setAlbumTitle(recent.getAlbumName());
                                    entity.setTrackTitle(recent.getTrackName());
                                    entity.setPlayBeginAt(recent.getTimeStamp());
                                    if (recent.getCurrentDuration() / 1000 == 0) {
                                        entity.setPlayedSecs(1);
                                    } else {
                                        entity.setPlayedSecs(recent.getCurrentDuration() / 1000);
                                    }
                                    entity.setPlayEndAt(entity.getPlayBeginAt() + entity.getPlayedSecs() * 1000);
                                    entity.setTrackCoverUrlLarge(recent.getCover());
                                } else {
                                    entity.setContentType(2);
                                    entity.setRadioId(recent.getAlbumId());
                                    entity.setScheduleId(recent.getTrackId());
                                    entity.setRadioName(recent.getAlbumName());
                                    entity.setProgramName(recent.getTrackName());
                                    entity.setPlayBeginAt(recent.getTimeStamp());
                                    if (recent.getCurrentDuration() / 1000 == 0) {
                                        entity.setPlayedSecs(1);
                                    } else {
                                        entity.setPlayedSecs(recent.getCurrentDuration() / 1000);
                                    }
                                    entity.setPlayEndAt(entity.getPlayBeginAt() + entity.getPlayedSecs() * 1000);
                                    entity.setRadioCoverUrlLarge(recent.getCover());
                                }
                                history.add(entity);
                            }












                            HttpClient.SyncPlayHistory(new Gson().toJson(history), new StringCallback() {
                                @Override
                                public void onError(Call call, Exception e, int id) {
                                }

                                @Override
                                public void onResponse(String response, int id) {
                                    Logger.i(response.toString());
                                    BaseBean resBean = new Gson().fromJson(response, BaseBean.class);
                                    if (resBean.getCode() == 0) {
                                        getData();
                                    }
                                }
                            });
                        } else {
                            getData();
                        }
                    }
                });
            }
        }
    }

}
